package com.yuanzi.base.filter;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.yuanzi.base.util.LogUtils;

/**
 * 请求信息打印<br>
 * @author chengshx
 * @date 2017年7月17日
 *
 */
public class RequestFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getRequestURI();
		String apiName = uri.substring(uri.indexOf("/") + 1);
		// 打印接口请求参数
		if(!Objects.equals(apiName, "favicon.ico")) {
			StringBuilder paramBuilder = new StringBuilder();
			Map<String, String[]> params = req.getParameterMap();
			params.forEach((key, value) -> {
				paramBuilder.append(key);
				paramBuilder.append("=");
				JSONArray paramArr = (JSONArray) JSONArray.toJSON(value);
				paramBuilder.append(paramArr.toJSONString());
				paramBuilder.append(",");
			});
			String paramStr = paramBuilder.length() > 0 ? paramBuilder.substring(0, paramBuilder.length() - 1) : "";
			LogUtils.info(this.getClass(), "{} : {}", apiName, paramStr);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}
	
}
